import sys
import random
from PyQt6.QtGui import QColor, QIcon
from PyQt6.QtWidgets import (
    QMainWindow, QApplication, QGraphicsDropShadowEffect, QDialog, QVBoxLayout,
    QLabel, QWidget
)
from PyQt6.QtCore import (
    Qt, QUrl, QPropertyAnimation, QEasingCurve, QVariantAnimation, QPoint, QSize, QEvent
)
from PyQt6.QtWebEngineWidgets import QWebEngineView

from out_maxxer_tool import MainWindow as OutMaxxxerWindow
from SSDDCleaner import MainWindow as SSDDCleanerWindow
from UI.mainWindow import Ui_MainWindow


class Snowflake(QLabel):
    """单个雪花"""
    def __init__(self, parent=None, size=6):
        super().__init__(parent)
        self.size = size
        self.setFixedSize(size, size)
        self.setStyleSheet(f"background-color: rgba(255,255,255,200); border-radius: {size//2}px;")

        self.anim = QPropertyAnimation(self, b"pos", self)
        self.anim.setLoopCount(1)  # 每次落到底部就结束，再重新调用 start

    def start(self, parent_width, parent_height, delay_ms=0):
        """雪花从顶部随机位置落到底部"""
        start_x = random.randint(0, max(1, parent_width - self.size))
        start_y = -self.size
        end_y = parent_height + self.size

        self.anim.stop()
        self.anim.setStartValue(QPoint(start_x, start_y))
        self.anim.setEndValue(QPoint(start_x + random.randint(-30, 30), end_y))
        self.anim.setDuration(random.randint(6000, 15000))  # 稍微拉长时长
        self.anim.setEasingCurve(QEasingCurve.Type.Linear)

        try:
            self.anim.finished.disconnect()
        except Exception:
            pass
        self.anim.finished.connect(
            lambda: self.start(parent_width, parent_height, delay_ms)
        )

        if delay_ms:
            from PyQt6.QtCore import QTimer
            QTimer.singleShot(delay_ms, self.anim.start)
        else:
            self.anim.start()


class WebPopupDialog(QDialog):
    """用于显示网页的弹窗（你的原样式）"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("TKM Metrics")
        # 获取屏幕分辨率
        self.screen_size = QApplication.primaryScreen().size()
        self.resize(self.screen_size.width(), self.screen_size.height())
        # self.resize(1200, 800)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        self.web_view = QWebEngineView()
        self.web_view.load(QUrl("https://www.baidu.com/"))
        layout.addWidget(self.web_view)


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        # 保留你的 Frameless / 阴影 / 拖动设置
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        self.setWindowIcon(QIcon('UI/icon002.ico'))
        shadow = QGraphicsDropShadowEffect(self)
        shadow.setBlurRadius(30)
        shadow.setXOffset(0)
        shadow.setYOffset(0)
        shadow.setColor(QColor(0, 0, 0, 180))
        self.centralwidget.setGraphicsEffect(shadow)

        # 原本的弹窗与外部窗口引用
        self.web_popup = None
        self.out_maxxxer_window = None

        # 悬浮粒子层和按钮动画状态容器
        self._particle_layer = None
        self._particles = []
        self._button_animations = dict()  # button -> dict of animations

        # 初始化交互
        self.init_signals()

        # 添加粒子层（放在 centralwidget 内，且在按钮层之下）
        # self._setup_particle_layer(num_snowflakes=30)
        self.horizontalLine.setStyleSheet("""
            QFrame {
                border: none;
                border-top: 1px solid white;
            }
        """)
        # 确保横线在雪花层上方
        self.horizontalLine.raise_()
        self._setup_line_effect()
        # 给中间的 8 个 QPushButton 添加动效（不改样式表）
        self._setup_pushbutton_effects()

    def init_signals(self):
        # 保留你之前的按钮连接：OutMaxxxer 和 PowerBI（如果你想改可以在这里调整）
        try:
            self.pushButton.clicked.connect(self.start_out_maxxxer)
            self.pushButton_2.clicked.connect(self.start_web_popup)
            self.pushButton_3.clicked.connect(self.start_ssdd_cleaner)
        except Exception:
            # 若控件名不一致，跳过连接（以免程序崩溃）
            pass

    def start_out_maxxxer(self):
        self.out_maxxxer_window = OutMaxxxerWindow()
        self.out_maxxxer_window.show()
        self.showMinimized()

    def start_web_popup(self):
        if not self.web_popup:
            self.web_popup = WebPopupDialog(self)
        self.web_popup.show()
        self.web_popup.raise_()
        self.web_popup.activateWindow()

    def start_ssdd_cleaner(self):
        self.ssdd_cleaner_window = SSDDCleanerWindow()
        self.ssdd_cleaner_window.show()
        self.showMinimized()

    # -------------------- 粒子层 --------------------
    def _setup_particle_layer(self, num_snowflakes=30):
        """全屏雪花效果"""
        self._particle_layer = QWidget(self.centralwidget)
        self._particle_layer.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)
        self._particle_layer.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground, True)
        self._particle_layer.setGeometry(self.centralwidget.rect())
        self._particle_layer.raise_()

        self._snowflakes = []
        for i in range(num_snowflakes):
            size = random.choice([4, 6, 8])
            flake = Snowflake(self._particle_layer, size=size)
            delay = random.randint(0, 4000)
            flake.start(self._particle_layer.width(), self._particle_layer.height(), delay)
            self._snowflakes.append(flake)

    def _setup_line_effect(self):
        """给横线加更明显的发光呼吸效果"""
        glow = QGraphicsDropShadowEffect(self.horizontalLine)
        glow.setOffset(0, 0)
        glow.setBlurRadius(35)  # 光晕范围更大
        glow.setColor(QColor(200, 50, 255, 120))  # 更亮的紫粉色
        self.horizontalLine.setGraphicsEffect(glow)

        # 呼吸动画：透明度变化更大
        anim = QVariantAnimation(self)
        anim.setStartValue(60)  # 最弱光
        anim.setEndValue(255)  # 最强光
        anim.setDuration(2500)  # 呼吸速度稍慢，显得柔和
        anim.setLoopCount(-1)
        anim.setEasingCurve(QEasingCurve.Type.InOutQuad)

        anim.valueChanged.connect(
            lambda v: glow.setColor(QColor(200, 50, 255, int(v)))
        )

        anim.start()
        self._line_anim = anim  # 保存引用

    def resizeEvent(self, event):
        """确保雪花层覆盖整个 centralwidget，并更新雪花范围"""
        super().resizeEvent(event)
        if hasattr(self, "_particle_layer") and self._particle_layer:
            self._particle_layer.setGeometry(self.centralwidget.rect())
            # 更新每个雪花的范围
            for flake in getattr(self, "_snowflakes", []):
                flake.start(self._particle_layer.width(), self._particle_layer.height())

    # -------------------- 按钮动效 --------------------
    def _setup_pushbutton_effects(self):
        """为中间的 8 个 QPushButton 添加 hover / click 动画（不修改样式表）"""
        # 列出你 UI 中的 8 个按钮（与 mainWindow.py 中命名对应）
        btn_names = [
            "pushButton_5",
            "pushButton",
            "pushButton_2",
            "pushButton_3",
            "pushButton_4",
            "pushButton_6",
            "pushButton_7",
            "pushButton_8",
        ]
        for name in btn_names:
            btn = getattr(self, name, None)
            if not btn:
                continue
            # 小手光标
            btn.setCursor(Qt.CursorShape.PointingHandCursor)

            # 添加一个轻微的阴影（用于 glow），颜色选用偏青色/青绿色，与深紫背景对比强但不改变按钮本身颜色
            effect = QGraphicsDropShadowEffect(btn)
            effect.setOffset(0, 0)
            effect.setBlurRadius(6)  # 初始弱光
            effect.setColor(QColor(0, 200, 220, 90))
            btn.setGraphicsEffect(effect)

            # 准备动画： blur up/down, alpha up/down, icon size up/down
            # 使用 QVariantAnimation 以在每一帧里设置 effect 的属性（避免属性不可动画的问题）
            blur_up = QVariantAnimation(self)
            blur_up.setStartValue(6)
            blur_up.setEndValue(22)
            blur_up.setDuration(220)
            blur_up.valueChanged.connect(lambda v, e=effect: e.setBlurRadius(float(v)))
            blur_up.setEasingCurve(QEasingCurve.Type.OutCubic)

            blur_down = QVariantAnimation(self)
            blur_down.setStartValue(22)
            blur_down.setEndValue(6)
            blur_down.setDuration(220)
            blur_down.valueChanged.connect(lambda v, e=effect: e.setBlurRadius(float(v)))
            blur_down.setEasingCurve(QEasingCurve.Type.OutCubic)

            alpha_up = QVariantAnimation(self)
            alpha_up.setStartValue(90)
            alpha_up.setEndValue(240)
            alpha_up.setDuration(220)
            alpha_up.valueChanged.connect(lambda v, e=effect: e.setColor(QColor(0, 200, 220, int(v))))
            alpha_up.setEasingCurve(QEasingCurve.Type.OutCubic)

            alpha_down = QVariantAnimation(self)
            alpha_down.setStartValue(240)
            alpha_down.setEndValue(90)
            alpha_down.setDuration(220)
            alpha_down.valueChanged.connect(lambda v, e=effect: e.setColor(QColor(0, 200, 220, int(v))))
            alpha_down.setEasingCurve(QEasingCurve.Type.OutCubic)

            # 图标尺寸动画（基于当前 iconSize，非布局尺寸变动）
            base_icon_size = btn.iconSize()
            if base_icon_size.isEmpty():
                base_w = base_h = 48
            else:
                base_w = base_icon_size.width()
                base_h = base_icon_size.height()
            icon_up = QVariantAnimation(self)
            icon_up.setStartValue(base_w)
            icon_up.setEndValue(int(base_w * 1.18))  # 约放大 18%
            icon_up.setDuration(220)
            icon_up.valueChanged.connect(lambda v, b=btn: b.setIconSize(QSize(int(v), int(v))))
            icon_up.setEasingCurve(QEasingCurve.Type.OutCubic)

            icon_down = QVariantAnimation(self)
            icon_down.setStartValue(int(base_w * 1.18))
            icon_down.setEndValue(base_w)
            icon_down.setDuration(220)
            icon_down.valueChanged.connect(lambda v, b=btn: b.setIconSize(QSize(int(v), int(v))))
            icon_down.setEasingCurve(QEasingCurve.Type.OutCubic)

            # 保存动画引用，防止被垃圾回收
            self._button_animations[btn] = {
                "effect": effect,
                "blur_up": blur_up,
                "blur_down": blur_down,
                "alpha_up": alpha_up,
                "alpha_down": alpha_down,
                "icon_up": icon_up,
                "icon_down": icon_down,
            }

            # 事件过滤器以捕获 enter/leave/press/release
            btn.installEventFilter(self)

    def eventFilter(self, obj, event):
        """处理按钮的 hover / press 动画（由 installEventFilter 注册）"""
        if obj in self._button_animations:
            anims = self._button_animations[obj]
            # 鼠标进入
            if event.type() == QEvent.Type.Enter:
                anims["blur_down"].stop()
                anims["alpha_down"].stop()
                anims["icon_down"].stop()
                anims["blur_up"].start()
                anims["alpha_up"].start()
                anims["icon_up"].start()
            # 鼠标离开
            elif event.type() == QEvent.Type.Leave:
                anims["blur_up"].stop()
                anims["alpha_up"].stop()
                anims["icon_up"].stop()
                anims["blur_down"].start()
                anims["alpha_down"].start()
                anims["icon_down"].start()
            # 按下：快速缩小图标（手感）
            elif event.type() == QEvent.Type.MouseButtonPress:
                if hasattr(event, "button") and event.button() == Qt.MouseButton.LeftButton:
                    # 快速缩小再恢复到 hover 状态
                    current_icon_w = obj.iconSize().width()
                    press_anim = QVariantAnimation(self)
                    press_anim.setStartValue(current_icon_w)
                    press_anim.setEndValue(max(28, int(current_icon_w * 0.85)))
                    press_anim.setDuration(100)
                    press_anim.valueChanged.connect(lambda v, b=obj: b.setIconSize(QSize(int(v), int(v))))
                    press_anim.setEasingCurve(QEasingCurve.Type.OutQuad)

                    # 在按下后短暂停，再放大回去（回到 hover 状态或正常状态）
                    def on_release_restore():
                        # 若鼠标仍在按钮上，放回 hover 大小，否则回到基础大小
                        # 检查 underMouse 状态简单判断
                        if obj.underMouse():
                            self._button_animations[obj]["icon_up"].start()
                            self._button_animations[obj]["blur_up"].start()
                            self._button_animations[obj]["alpha_up"].start()
                        else:
                            self._button_animations[obj]["icon_down"].start()
                            self._button_animations[obj]["blur_down"].start()
                            self._button_animations[obj]["alpha_down"].start()

                    # 保持引用防回收
                    obj._press_anim = press_anim
                    press_anim.finished.connect(on_release_restore)
                    press_anim.start()
            # 鼠标释放：不必处理过多（press 动画会自己在 finished 中触发恢复）
            return False

        return super().eventFilter(obj, event)

    # 拖动窗口
    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self.drag_position = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.MouseButton.LeftButton:
            self.move(event.globalPosition().toPoint() - self.drag_position)
            event.accept()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
